<template>
  <div class="app-container">
    <el-row :gutter="24">
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入" clearable style="width: 240px" maxlength="30"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="权限字符" prop="authorityChar">
            <el-input v-model="queryParams.authorityChar" placeholder="请输入" clearable style="width: 240px" maxlength="30"
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="创建时间" prop="time">
            <el-date-picker v-model="queryParams.time" value-format="YYYY-MM-DD HH:mm:ss" type="daterange"
              start-placeholder="开始日期" end-placeholder="结束日期"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" />
          </el-form-item>
          <el-form-item style="margin-left: 40px;">
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button type="success" icon="Plus" @click="handleAdd">新增</el-button>
          </el-form-item>
        </el-form>

        <el-table v-loading="loading" :data="roleData"
          style="margin-top: 10px;margin-left: 20px;margin-right: 20px;width: calc(100% - 40px);">
          <el-table-column type="index" width="100" label="角色编号" />
          <el-table-column label="角色名称" align="center" prop="name" />
          <el-table-column label="权限字符" align="center" prop="authorityChar" />
          <el-table-column label="显示顺序" align="center" prop="sort" />
          <el-table-column label="权限" align="center" prop="authorityName" />
          <el-table-column label="备注" align="center" prop="description" />
          <el-table-column label="操作" fixed="right" align="center" width="120" class-name="small-padding fixed-width">
            <template #default="scope">
              <!-- <el-button link type="success" @click="handleLook(scope.row)">查看</el-button> -->
              <el-button link type="primary" @click="handleEdit(scope.row)">修改</el-button>
              <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
          @pagination="getList" style="margin-right: 20px;" />
      </el-col>
    </el-row>

    <!-- 添加 -->
    <el-dialog v-model="open" width="600px" append-to-body :title="form.id ? '编辑' : '新增'">
      <div v-loading="dialogloading">
        <el-form :model="form" :rules="rules" ref="userRef" label-width="120px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" remote-method placeholder="请输入" style="width: 400px" maxlength='11' />
          </el-form-item>
          <el-form-item label="权限字符" prop="authorityChar">
            <el-input v-model="form.authorityChar" placeholder="请输入" style="width: 400px" maxlength='11' />
          </el-form-item>
          <el-form-item label="角色顺序" prop="sort">
            <el-input-number v-model="form.sort" :min="1" :step="1" :precision="0" :max="10" controls-position="right"
              style="width: 200px" />
          </el-form-item>
          <el-form-item label="菜单权限" prop="authorityId">
            <div class="tree">
              <el-tree ref="treeRef" :props="props" :data="menuProps" show-checkbox node-key="id" empty-text="加载中，请稍等" />
            </div>
          </el-form-item>
          <el-form-item label="备注" prop="description">
            <el-input v-model="form.description" placeholder="请输入" :autosize="{ minRows: 2, maxRows: 4 }" type="textarea"
              style="width: 400px" maxlength='200' show-word-limit />
          </el-form-item>
        </el-form>
        <div class="dialog-footer">
          <el-button type="primary" @click="saveForm">确认</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { apiRoleSearchList, apiRoleMenuList, apiRoleCreate, apiRoleDelete, apiRoleUpdate } from "@/api/authority";
const { proxy } = getCurrentInstance();

const roleData = ref([]);
const loading = ref(false);
const open = ref(false);
const dialogloading = ref(false);
const total = ref(0);
const treeRef = ref()

const props = {
  children: 'children',
  label: 'name',
  value: 'id',
  isLeaf: 'leaf',
}

const menuProps = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
  },
  rules: {
    name: [{ required: true, message: "请输入", trigger: "change" }],
    authorityChar: [{ required: true, message: "请输入", trigger: "blur" }],
    sort: [{ required: true, message: "请输入", trigger: "blur" }],
    authorityId: [{ required: true, message: "请选择", trigger: "change" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询列表 */
const getList = () => {
  loading.value = true;
  apiRoleSearchList(queryParams.value).then(res => {
    loading.value = false;
    if (res.data) {
      roleData.value = res.data.records;
      total.value = res.data.total;
    } else {
      roleData.value = []
      total.value = 0
    }
  }).catch(err => {
    loading.value = false
    roleData.value = []
    total.value = 0
  });
};

getList();

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
};


/** 重置操作表单 */
function reset() {
  form.value = {
    name: undefined,
    authorityChar: undefined,
    sort: undefined,
    authorityId: undefined,
    description: undefined
  };
  proxy.resetForm("userRef");
  treeRef.value?.setCheckedNodes([])
};
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
};
/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  form.value = {}
  open.value = true
  getMenuData()
};

const handleEdit = (row) => {
  reset();
  form.value = row
  open.value = true
  let menuIds = row.authorityId
  getMenuData(menuIds)
};

/** 树形数据 */
const getMenuData = (ids) => {
  apiRoleMenuList().then(res => {
    if (res.data) {
      menuProps.value = res.data
      setTimeout(() => {
        ids.forEach((item) => {
          treeRef.value.setChecked(item, true, false);
        });
      }, 100)
    }
  }).catch(err => { });
};


const saveForm = () => {
  proxy.$refs["userRef"].validate(valid => {
    if (valid) {
      let keyData = [
        ...treeRef.value.getCheckedKeys(false),
        ...treeRef.value.getHalfCheckedKeys()
      ]
      form.value.authorityId = keyData.join(',')
      if (form.value.id) {
        apiRoleUpdate(form.value).then(res => {
          dialogloading.value = false;
          proxy.$modal.msgSuccess("操作成功");
          open.value = false;
          getList()
        }).catch(err => {
          dialogloading.value = false
        });
      } else {
        apiRoleCreate(form.value).then(res => {
          dialogloading.value = false;
          proxy.$modal.msgSuccess("操作成功");
          open.value = false;
          getList()
        }).catch(err => {
          dialogloading.value = false
        });
      }
    }
  })
};


const handleDelete = (row) => {
  proxy.$modal.confirm('是否确认删除该数据项？').then(() => {
    return apiRoleDelete(row.id)
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

</script>


<style lang="scss" scoped>
.dialog-item-title {
  color: #000;
  font-size: 17px;
  padding-left: 10px;
  margin: 0 20px;
  border-left: 4px #00BFFF solid;
}

.tree {
  width: 100%;
  height: 300px;
  overflow-y: scroll;
  border: 1px solid #ddd;
}

.now-select-txt {
  font-size: 15px;
  color: #fff;
  background: #00BFFF;
  padding: 10px 20px;
  border-radius: 10px 10px 0 0;

  span {
    font-size: 20px;
    font-weight: bold;
    margin: 0 10px;
  }

  div {
    cursor: pointer;
    margin-left: 30px;
    font-weight: bold;
  }
}
</style>